<template>
  <div class="over-container" v-loading="isloading">
    <div class="over-header">
      <div class="header"><i class="el-icon-d-arrow-right" />按条件筛选</div>
      <div class="search">
        <div class="zahungtai">
          <i class="el-icon-star-on"></i><span>&emsp;状态：</span>
          <el-radio-group
            v-model="listquery.agreeType"
            size="small"
            @change="getdata"
          >
            <el-radio label="1" border>授权通过</el-radio>
            <el-radio label="-1" border>未通过授权</el-radio>
            <el-radio label="" border>全部</el-radio>
          </el-radio-group>
        </div>
      </div>
    </div>
    <div class="header">
      <i class="el-icon-d-arrow-right"></i>设备授权已办记录
    </div>
    <!-- :tableData="result.slice((curPage - 1) * pageSize, curPage * pageSize)" -->
    <el-table
      :data="tableData"
      stripe
      border
      style="width: 100%"
      class="eltable"
    >
      <el-table-column label="序号" width="100" type="index" />
      <el-table-column prop="applyDate" label="申请时间" width="150" sortable />
      <el-table-column prop="applyFiles" label="设备信息" width="80">
        <template slot-scope="scope">
          <el-tooltip
            class="item"
            effect="dark"
            content="查看设备信息附件"
            placement="bottom"
          >
         <a :href="getShebeiUrl(scope.row.applyFiles)" download><i class="iconfont icon-shebei"></i></a>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="keyFile" label="中标合同" width="80">
        <template slot-scope="scope">
          <el-tooltip
            class="item"
            effect="dark"
            content="查看中标合同附件"
            placement="bottom"
          >
           <a :href="getHetongUrl(scope.row.applyFiles)" :download="getHetongUrl(scope.row.applyFiles)"><i class="iconfont icon-hetong"></i></a>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="责任人号码" width="150" />
   
      <el-table-column prop="agreeType" label="状态" width="120" sortable>
        <template scope="scope">
          <span v-if="scope.row.agreeType == '1'" style="color: green"
            >授权通过</span
          >

          <span v-if="scope.row.agreeType == '-1'" style="color: red"
            >未通过</span
          >
        </template>
      </el-table-column>

      <el-table-column prop="agreeUserName" label="授权人" width="120" />
      <el-table-column prop="agreeDate" label="授权时间" width="200" sortable />
      <el-table-column label="授权文件||未通过原因" fixed="right">
        <template scope="scope">
          <el-tooltip
            class="item"
            effect="dark"
            content="下载授权文件"
            placement="bottom"
          >
            <el-button
              v-if="scope.row.agreeType == 1"
              type="primary"
              icon="el-icon-s-order"
              plain
              @click="downloadwenjian(scope.row.keyFile)"
              circle
            >
            </el-button>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="未通过原因"
            placement="bottom"
          >
            <el-button
              v-if="scope.row.agreeType == -1"
              type="primary"
              icon="el-icon-s-comment"
              plain
              @click="showMessage(scope.row.message)"
              circle
            >
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
      <!-- <el-table-column label="操作" width="180">
        <template scope="scope">
          <el-tooltip
            v-if="scope.row.agreeType == '1'"
            class="item"
            effect="dark"
            content="补录村庄"
            placement="top-start"
          >
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              circle
              @click="openChangeDialog(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column> -->
    </el-table>
    <el-pagination
      class="elpagi"
      :total="total"
      @size-change="getdata"
      @current-change="getdata"
      @prev-click="getdata"
      @next-click="getdata"
      :current-page.sync="listquery.currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size.sync="listquery.pageSize"
      layout="total,sizes, prev, pager, next, jumper"
    />
    <!-- 村庄列表弹出框 -->
    <el-dialog
      title="村庄列表"
      :visible.sync="dialogVisible"
      width="30%"
      append-to-body
    >
      <ul>
        <li v-for="item in allvilages" :key="item">{{ item }}</li>
      </ul>
    </el-dialog>
    <!-- 村庄列表弹出框 -->
    <el-dialog
      title="村庄补录"
      :visible.sync="changeDialogVisible"
      width="30%"
      append-to-body
      v-loading="cascaderLoading"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      v-loading.fullscreen.lock="true"
    >
      <ul v-if="allvilages.length > 0">
        <div class="allvilagestitle">已选村庄列表如下所示:</div>
        <li v-for="item in allvilages" :key="item">{{ item }}</li>
      </ul>
      <el-cascader
        v-if="changeDialogVisible"
        v-model="citySelected"
        :options="countyList"
        :props="props"
        size="medium"
        placeholder="请选择关联村庄"
        clearable
        collapse-tags
        :show-all-levels="false"
        @change="handleChange"
        @expand-change="onExpandChange"
        class="cascader"
      ></el-cascader>
      <div slot="footer" class="dialog-footer">
        <el-button @click="changeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeSubmit">确认修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import tableHeader from "../components/TableHeader";
import { dataagreedolist, changeVillages } from "@/api/index.js";
import { export_json_to_excel } from "@/utils/export2Excel.js";
import openMixin from "@/mixins/open.js";
import {
  getTownList,
  getAllVillageList,
  getAllVillageListSkip,
} from "@/api/country.js";
import { picHost } from "@/settings.js";
import { mapGetters } from "vuex";
export default {
  computed: {
    ...mapGetters(["citylist"]),
  },
  components: {
    tableHeader,
  },
    mixins: [openMixin],
  data() {
    return {
      name: "",
      listquery: {
        pageSize: 10,
        currentPage: 1,
        city: null,
        country: null,
        key: "",
        agreeType: "",
      },
      isloading: false,
      total: 0,
      tableData: [],
      dialogVisible: false,
      changeDialogVisible: false,
      allvilages: [],
      citySelected: [],
      countrySelected: [],
      cascaderLoading: false,
      props: {
        emitPath: false,
        lazy: false,
        multiple: true,
      },
    };
  },
  mounted() {
    this.getdata();
    // citys.children.forEach(v => {
    //   v.value = v.label
    //   v.children.forEach(i => {
    //     i.value = i.label
    //     i.leaf = false
    //     i.children = []
    //   })
    // })
  },
  methods: {
    async getdata() {
      this.isloading = true;
      let res = await dataagreedolist(this.listquery);
      if (res.success) {
        this.tableData = res.data.content;
        this.total = res.data.totalElements;
        this.isloading = false;
      } else {
        this.tableData = [];
      }
    },
    //表格属性排序
    sortChange(data) {
      const { prop, order } = data;
      this.listquery.sortby = prop;
      this.listquery.sortorder = order;
      this.getData();
    },

    downloadwenjian(keyFile) {
      window.open(picHost + keyFile);
    },
    download() {
      let query = {
        pageSize: 99999,
        currentPage: 1,
        city: null,
        country: null,
        key: this.listquery.key,
      };
      this.isloading = true;
      dataagreedolist(query).then((res) => {
        let tablelist = res.data.content;
        this.downloadExcel(tablelist);
        this.isloading = false;
      });
    },
    downloadExcel(tabledatalist) {
      let header = Object.keys(tabledatalist[0]);
      let list2 = [];
      for (var i = 0; i < tabledatalist.length; i++) {
        let list1 = [];
        for (var j = 0; j < header.length; j++) {
          let obj = tabledatalist[i];
          list1.push(obj[header[j]]);
        }
        list2.push(list1);
      }
      export_json_to_excel({
        header: header,
        data: list2,
        filename: "数据申请已办箱",
      });
    },
    //查看未通过原因
    showMessage(message) {
      this.$alert(message, "未通过审核", {
        confirmButtonText: "确定",
      });
    },
    openMore(villages) {
      this.changeDialogVisible = true;
      this.allvilages = villages;
    },
    beforeClose() {},
    handleChange(e) {},
    onExpandChange(e) {
      if (e.length == 2) {
        this.cascaderLoading = true;
        let city = e[0];
        let country = e[1];
        let currentNodeIndex = this.getCurrentNode(e);
        let node =
          this.countyList[currentNodeIndex[0]].children[currentNodeIndex[1]];
        if (node.isLoaded) {
          this.cascaderLoading = false;
          return;
        }
        getTownList({
          city: city,
          country: country,
        }).then((res) => {
          let nodes = [];
          let promiseArrary = [];
          res.data.map((v, i) => {
            let n = {
              id: i,
              label: v,
              value: v,
              children: [],
            };
            let promise = getAllVillageList({
              city: city,
              country: country,
              town: v,
            }).then((response) => {
              return response;
            });
            if (node.children.length > 0) {
              node.children.forEach((item) => {
                if (res.data.indexOf(item.label) == -1) {
                  promiseArrary.push(promise);
                  nodes.push(n);
                }
              });
            } else {
              promiseArrary.push(promise);
              nodes.push(n);
            }
          });
          Promise.all(promiseArrary).then((dataArr) => {
            if (dataArr.length > 0) {
              nodes.forEach((v, i) => {
                let data = dataArr[i];
                v.children = data.data.map((item, index) => {
                  return {
                    id: index,
                    label: item[1],
                    value: item[0],
                    leaf: true,
                  };
                });
              });
            }
            node.children.push(...nodes);
            node.isLoaded = true;
            this.cascaderLoading = false;
          });
        });
      }
    },
    getCurrentNode(e) {
      let city = e[0];
      let country = e[1];
      let result = [];
      this.countyList.forEach((v, i) => {
        if (v.label == city) {
          result.push(i);
          v.children.forEach((item, index) => {
            if (item.label == country) {
              result.push(index);
            }
          });
        }
      });
      return result;
    },
    // 修改按钮弹窗
    openChangeDialog(row) {
      this.row = row;
      this.countyList = JSON.parse(JSON.stringify(this.citylist));
      this.allvilages = row.villages;
      this.countrySelected = row.villageIds ? row.villageIds.split(",") : [];
      let townList = row.villages.map((v) => {
        return v.split("-")[0] + "-" + v.split("-")[1] + "-" + v.split("-")[2];
      });
      let townSet = Array.from(new Set(townList));
      this.citySelected = row.villageIds ? row.villageIds.split(",") : [];
      let promiseArrary = [];
      townSet.forEach((v) => {
        let city = v.split("-")[0];
        let country = v.split("-")[1];
        let town = v.split("-")[2];
        this.countyList.forEach((item, i) => {
          if (item.label == city) {
            item.children.forEach((countryItem, countryIndex) => {
              if (countryItem.label == country) {
                if (!countryItem.children) {
                  countryItem.children = [
                    {
                      id: "",
                      label: town,
                      value: town,
                      children: [],
                    },
                  ];
                } else {
                  countryItem.children.push({
                    id: "",
                    label: town,
                    value: town,
                    children: [],
                  });
                }
                let index = countryItem.children.length - 1;
                let promise = getAllVillageList({
                  city: city,
                  country: country,
                  town: town,
                }).then((response) => {
                  return { level: [i, countryIndex, index], response };
                });
                promiseArrary.push(promise);
              }
            });
          }
        });
      });
      Promise.all(promiseArrary).then((datas) => {
        datas.forEach((v) => {
          this.countyList[v.level[0]].children[v.level[1]].children[
            v.level[2]
          ].children = v.response.data.map((item) => {
            return {
              id: item[0],
              label: item[1],
              value: item[0],
              leaf: true,
            };
          });
        });
        this.changeDialogVisible = true;
      });
    },
    changeSubmit() {
      let id = this.row.id;
      let ids = "";
      this.citySelected.forEach((v) => {
        ids += v + ",";
      });
      changeVillages({
        id: id,
        ids: ids.substring(0, ids.length - 1),
      })
        .then((res) => {
          if (res.success) {
            this.$notify({
              title: "成功",
              message: "修改成功",
              type: "success",
            });
            this.changeDialogVisible = false;
            this.getdata();
          } else {
            this.$notify.error({
              title: "错误",
              message: res.message,
            });
          }
        })
        .catch((er) => {
          console.log(er);
          this.$notify.error({
            title: "错误",
            message: "请求错误，请重试",
          });
        });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "../../../../public/css/table.scss";
.cascader {
  margin-top: 20px;
}
.allvilagestitle {
  line-height: 35px;
  color: #4778c7;
}
ul {
  margin: 0;
  padding: 5px;
  list-style: none;
  max-height: 250px;
  overflow-y: auto;
  border: 1px dashed #ccc;
  li {
    line-height: 25px;
  }
}
::v-deep .el-dialog__title {
  font-size: 16px;
  color: #4cc8c7;
}
::v-deep .el-dialog__body {
  padding: 10px 20px;
  margin-top: -10px;
}
.over-container {
  margin: 5px;
  padding-bottom: 10px;
  overflow-y: auto;
  position: relative;
  height: 100%;
}

.downButton {
  background-color: #4778c7;
  color: #fff;
  border-radius: 5px;
  height: 32px;
  line-height: 32px;
  font-size: 14px;
  padding: 0px 15px;
  letter-spacing: 1px;
}
.vitotal {
  margin-left: 4px;
  color: #9370db;
}
.more {
  color: #4cc8c7;
  margin-left: 10px;
  &:hover {
    color: orange;
  }
}
.header {
  line-height: 35px;
  margin-right: 5px;
  i {
    color: #4778c7;
  }
}

.over-header {
  background-color: #fff;
  border-radius: 5px;
  margin-bottom: 15px;
  .header {
    border-bottom: 1px dashed #ccc;
  }
  .search {
    padding: 10px 20px;
    display: flex;
    justify-content: space-between;
  }
  .zahungtai {
    display: flex;
    align-items: center;
  }
}
</style>
